import axios, {InternalAxiosRequestConfig} from 'axios';
import type { AxiosResponse } from 'axios';
import { Message, Modal } from '@arco-design/web-vue';
import { useUserStore } from '@/store';
import { getToken } from '@/utils/auth';
import qs from "query-string";

export interface HttpResponse<T = unknown> {
  status: number;
  msg: string;
  code: number;
  data: T;
}

if (import.meta.env.VITE_API_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}

axios.interceptors.request.use(
    (config: InternalAxiosRequestConfig<any>) => {
      const token = getToken();
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      if (config.method === 'get' || config.method === 'delete') {
        config.paramsSerializer = (params) => {
          // @ts-ignore
          return qs.stringify(params, { arrayFormat: 'repeat' })
        }
      }
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
);
// add response interceptors
axios.interceptors.response.use(
  (response: AxiosResponse<any, any>) => {
    const res = response.data;
    // 根据状态码判断
    // 50001: 未登录;
    if ([50001].includes(res.code)) {
      const userStore = useUserStore();
      userStore.logoutCallBack();
      userStore.updateSettings();

      return Promise.reject();
    } else if (res.code === 500) {
      Message.warning({
        content: res.msg,
        duration: 2 * 1000,
      });
    } else if (res.code !== 200) {
      console.log(res.msg);
      Message.warning({
        content: res.msg,
        duration: 2 * 1000,
      });
    }
    return res;
  },
  (error) => {
    const res =  error.response;
    if (res.status === 401) {
      Modal.error({
        title: '系统提示',
        content:
            '您已登出，您可以取消留在该页面，或重新登录',
        okText: '重新登录',
        async onOk() {
          const userStore = useUserStore();

          userStore.logoutCallBack();
          window.location.reload();
        },
      });
    } else if (res.status === 404) {
      Message.warning({
        content: "请求路径不存在",
        duration: 2 * 1000,
      });
    } else if (res.status === 500) {
      Message.warning({
        content: "请求异常，请联系管理员",
        duration: 2 * 1000,
      });
    } else {
      Message.error({
        content: error.msg || 'Request Error',
        duration: 2 * 1000,
      });
    }
    return Promise.reject(error);
  }
);
